package org.superheroes.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.superheroes.net.discovery.DiscoveryHandler;

import android.util.Log;

/**
 * 
 * @author Jeffrey Goudzwaard
 * @author Davin Terrizzi
 * @version 1.0
 *
 */
public class StreamingServer
{
	private static final String LOG_TAG = StreamingServer.class.getName();
	private static final String LOG_ERROR_TAG = StreamingServer.class.getName() + ".error";
	
	private static final int SERVER_PORT = 3030;
	public static final int INIT = 0;
	public static final int READY = 1;
	public static final int PLAYING = 2;
	public static final int SETUP = 3;
	public static final int PLAY = 4;
	public static final int PAUSE = 5;
	public static final int TEARDOWN = 6;
	
	public static int MJPEG_TYPE = 26;
	public static int FRAME_PERIOD = 100;
	public static int VIDEO_LENGTH = 500;
	
	private ServerSocket listenSocket;
	
	private Runnable clientConnector;
	
	public StreamingServer()
	{
		discoveryInit();
		init();
	}
	
	private void discoveryInit()
	{
		new DiscoveryHandler();
	}
	
	/**
	 * Initializes the streaming server
	 */
	private void init()
	{
		clientConnector = new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					listenSocket = new ServerSocket( SERVER_PORT );
					
					Log.i( LOG_TAG, "TCP Listen socket created" );
					
					while( true )
					{
						Log.i( LOG_TAG, "Waiting for clients..." );
						Socket clientSocket = listenSocket.accept();
						Thread clientStreamThread = new ClientStreamThread( clientSocket );
						clientStreamThread.start();
					}
				}
				catch( IOException e )
				{
					Log.e( LOG_ERROR_TAG, e.toString() );
				}
			}
		};
		
		Thread clientConnectorThread = new Thread( clientConnector );
		clientConnectorThread.start();
	}
}
